package me.xuym.crawler.simpleextension.loader;

import com.cbs.java.component.application.Application;
import com.cbs.java.component.network.HttpClient;
import com.cbs.java.component.network.Request;
import com.cbs.java.component.network.Response;
import com.cbs.java.component.network.decoder.TextDecoder;
import me.xuym.crawler.Processor;

import java.net.InetSocketAddress;
import java.net.Proxy;

/**
 * Created by broche on 05/08/2017.
 */
public class SimpleWebPageLoader extends Processor<String, String> {
    private String url = "";
    private String charset = "utf-8";
    private String proxyHost = "";
    private int proxyPort = 0;

    private HttpClient httpClient;

    public SimpleWebPageLoader(Application application, String url, String charset, String proxyHost, int proxyPort) {
        super(application);

        this.url = url;
        this.charset = charset;
        this.proxyHost = proxyHost;
        this.proxyPort = proxyPort;

        HttpClient.Builder builder = new HttpClient.Builder();

        if (proxyHost != null && !proxyHost.equals("")) {
            builder.getOkBuilder().proxy(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyHost, proxyPort)));
        }
        httpClient = builder.build();
    }

    public SimpleWebPageLoader(Application application, String url) {
        this(application, url, "utf-8", "", 0);
    }

    public SimpleWebPageLoader(Application application, String url, String charset) {
        this(application, url, charset, "", 0);
    }

    public SimpleWebPageLoader(Application application, String url, String proxyHost, int proxyPort) {
        this(application, url, "utf-8", proxyHost, proxyPort);
    }

    @Override
    public String onProcess(String param) throws Exception {
        Request request = new Request(url).setDecoder(new TextDecoder(charset));
        Response response = httpClient.sendSync(request);
        String result = response.getResult().toString();
        return result;
    }
}
